package uk.ac.lkl.takteen.energyapp;

import uk.ac.lkl.takteen.energyapp.data.EnergyAppDatabaseMetadata;
import uk.ac.lkl.takteen.energyapp.data.EnergyAppProvider;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class SharedPledgeEditor extends Activity {

	private final int DIALOG_SAVE = 1;
	private EditText mPledgeName;
	private ImageView mPledgeImage;
	private Uri imageUri;

	private static final int COLUMN_INDEX_NAME = 1;
	private static final int COLUMN_INDEX_IMAGE = 2;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.received_item_editor);

		mPledgeName = (EditText) findViewById(R.id.received_item_name);
		mPledgeImage = (ImageView) findViewById(R.id.received_item_image);
		if (getIntent().getAction().equals(Intent.ACTION_SEND))
			imageUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
		else if (getIntent().getAction().equals(Intent.ACTION_VIEW)) {
			Cursor cursor = managedQuery(getIntent().getData(),
					EnergyAppDatabaseMetadata.PROJECTION_SHARED_PLEDGES, null,
					null, null);
			cursor.moveToFirst();

			mPledgeName.setText(cursor.getString(COLUMN_INDEX_NAME));
			mPledgeName.setInputType(InputType.TYPE_NULL);

			String imageUri_string = cursor.getString(COLUMN_INDEX_IMAGE);
			imageUri = Uri.parse(imageUri_string);
			if (imageUri_string != null)
				mPledgeImage.setImageURI(imageUri);

		}
		if (imageUri != null)
			mPledgeImage.setImageURI(imageUri);

		final Button acceptChallengeButton = (Button) findViewById(R.id.accept);
		acceptChallengeButton.setText("Save");
		acceptChallengeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				createSharedPledge();
				Intent intent = new Intent(Intent.ACTION_VIEW,
						EnergyAppProvider.SHARED_PLEDGES_DIR,
						SharedPledgeEditor.this, Pledges.class);
				intent.addFlags(2);
				startActivity(intent);
			}
		});

		final Button deleteChallengeButton = (Button) findViewById(R.id.delete);
		deleteChallengeButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DIALOG_SAVE);
			}
		});

		final Button sendMsgButton = (Button) findViewById(R.id.send_msg);
		sendMsgButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String mimetype;
				Intent intent = new Intent(Intent.ACTION_SEND);
				mimetype = "text/plain";
				intent.setType(mimetype);
				intent.putExtra(Intent.EXTRA_SUBJECT, mPledgeName.getText()
						.toString());
				try {
					startActivity(Intent.createChooser(intent, "Send to:"));
				} catch (android.content.ActivityNotFoundException ex) {
					Toast.makeText(SharedPledgeEditor.this,
							"No apps registered for this intent",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	private void createSharedPledge() {
		String name = mPledgeName.getText().toString();
		if (name.length() == 0)
			name = "Nameless pledge";
		ContentValues values = new ContentValues();
		Intent intent = getIntent();
		values.put(EnergyAppDatabaseMetadata.PLEDGE_NAME, name);
		values.put(EnergyAppDatabaseMetadata.PLEDGE_IMAGE, imageUri.toString());

		if (Intent.ACTION_SEND.equals(intent.getAction())) {
			getContentResolver().insert(EnergyAppProvider.SHARED_PLEDGES_DIR,
					values);
		} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
			String whenSelectionStatement = EnergyAppDatabaseMetadata._ID + "="
					+ intent.getData().getLastPathSegment();
			getContentResolver().update(getIntent().getData(), values,
					whenSelectionStatement, null);
		}
	}

	@Override
	public void onBackPressed() {
		Log.d("CDA", "onBackPressed Called");
		createSharedPledge();
		Intent intent = new Intent(Intent.ACTION_VIEW,
				EnergyAppProvider.SHARED_PLEDGES_DIR, SharedPledgeEditor.this,
				Pledges.class);
		intent.addFlags(2);
		startActivity(intent);
	}

	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch (id) {
		case DIALOG_SAVE:
			builder.setTitle("Save")
					.setMessage("Do you want to save this challenge?")
					.setPositiveButton("Save",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									createSharedPledge();
									dialog.cancel();
									Intent intent = new Intent(
											Intent.ACTION_VIEW,
											EnergyAppProvider.SHARED_PLEDGES_DIR,
											SharedPledgeEditor.this,
											Pledges.class);
									intent.addFlags(2);
									startActivity(intent);
								}
							})
					.setNegativeButton("Delete",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									if (getIntent().getAction().equals(
											Intent.ACTION_SEND)) {
										// do nothing, just don't save
										Intent intent = new Intent(
												Intent.ACTION_VIEW,
												EnergyAppProvider.SHARED_PLEDGES_DIR,
												SharedPledgeEditor.this,
												SharedPledgesList.class);
										startActivity(intent);
									} else if (getIntent().getAction().equals(
											Intent.ACTION_VIEW)) {
										String whenSelectionStatement = EnergyAppDatabaseMetadata._ID
												+ "="
												+ getIntent().getData()
														.getLastPathSegment();
										getContentResolver()
												.delete(EnergyAppProvider.SHARED_PLEDGES_DIR,
														whenSelectionStatement,
														null);
										dialog.cancel();
										Intent intent = new Intent(
												Intent.ACTION_VIEW,
												EnergyAppProvider.SHARED_PLEDGES_DIR,
												SharedPledgeEditor.this,
												Pledges.class);
										intent.addFlags(2);
										startActivity(intent);
									}
								}
							});
			break;
		default:

		}
		return builder.create();
	}
}
